#pragma once
#include "net.hpp"

namespace qiangsir
{
    class CallBack
    {
    public:
        using ptr = std::shared_ptr<CallBack>;
        virtual void onMessage(const BaseConnection::ptr &conn,  BaseMessage::ptr &msg) = 0;
    };
    template <typename T>
    class CallBackT : public CallBack
    {
    public:
        using ptr = std::shared_ptr<CallBackT<T>>;
        using MessageCallBack = std::function<void(const BaseConnection::ptr &conn, std::shared_ptr<T> &msg)>;
        CallBackT(const MessageCallBack handler) : _handler(handler) {}
        virtual void onMessage(const BaseConnection::ptr &conn, BaseMessage::ptr &msg) override
        {
            auto type_msg = std::dynamic_pointer_cast<T>(msg);
            _handler(conn, type_msg);
        }

    private:
        MessageCallBack _handler;
    };
    class Dispatcher
    {
    public:
        using ptr = std::shared_ptr<Dispatcher>;

        template <typename T>
        void registerHandler(MType mtype, const typename CallBackT<T>::MessageCallBack &handler)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto cb = std::make_shared<CallBackT<T>>(handler);
            _handlers.insert(std::make_pair(mtype, cb));
        }
        void onMessage(const BaseConnection::ptr &conn, BaseMessage::ptr &msg)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto pos = _handlers.find(msg->mtype());
            if (pos != _handlers.end())
            {
                return pos->second->onMessage(conn, msg);
            }
            ELOG("收到未知信息");
            conn->shutDown();
            return;
        }

    private:
        std::mutex _mutex;
        std::unordered_map<MType, CallBack::ptr> _handlers;
    };
}